<template>
    <div class="my_uploader">
        <div class="my_uploader_content relative" v-loading="loading" v-show="(limit && (!fileList.length || (fileList.length && fileList.length < limit))) || (!limit)">
            <slot name="uploader">
                <div class="uploader_box text-center relative">
                    <i class="uploader_icon el-icon-upload text-gray absolute"></i>
                </div>
            </slot>
            <input ref="myInputFileRef" type="file" class="my_file_input absolute pointer" :accept="accept" :multiple="multiple" @change="getInputFileChange($event)" v-if="!disabled">
        </div>

        <div class="preview_box" v-if="fileList && fileList.length">
            <div class="preview_img relative" :class="{'has_bgimg none_preview': !file.isImg}" v-for="(file, index) of fileList" :key="'myFileItem' + index">
                <el-image :src="file.fileFullUrl" :preview-src-list="[fileList[index].fileFullUrl]" v-if="file.isImg" fit="contain">
                    <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline"></i>
                        <p>加载失败</p>
                    </div>
                </el-image>

                <a v-else :href="file.fileFullUrl" target="_blank">{{file.fileType}}</a>

                <i class="el-icon-delete pointer absolute" @click="deleteImg(index, file.fileFullUrl)" v-if="!disabled"></i>
            </div>
        </div>
    </div>
</template>

<script>
import { PublicUploadFileItemZip } from '@/api/PublicServices';
export default {
    name: 'AppUploaderZip',
    props: {
        title: {
            type: String,
            default: '附件'
        },
        disabled: {
            type: Boolean,
            default: false
        },
        limit: {
            type: Number,
            default: 20
        },
        accept: {
            type: String,
            default: '*'
        },
        fileFormat: {
            type: Array,
            default: null
        },
        multiple: {
            type: Boolean,
            default: false
        },
        initFiles: {
            type: Array | Object,
            default: null // [string]
        },
        path: {
            type: String,
            default: 'middleground/public/upload'
        }
    },
    data() {
        return {
            fileList: [],
            loading: false,
            baseUrl: process.env.VUE_APP_FILE_URL,
            imgFormat: ['gif', 'svg', 'jpg', 'jpeg', 'png', 'ico']
        }
    },
    watch: {
        initFiles: {
            immediate: true,
            handler(newValue) {
                this.fileList = [];
                if (!newValue || !newValue.length) return;
                // 过滤，有效的图片地址
                const filerList = newValue.filter(item => item);
                if (filerList && filerList.length) {
                    this.fileList = filerList.map(item => {
                        if (item.indexOf(this.baseUrl) >= 0) {
                            const fileUrl = item.splice(this.baseUrl + '/')[1];
                            const fileType = this.getFileFormat(fileUrl);
                            return {
                                fileUrl: fileUrl,
                                fileBaseUrl: this.baseUrl,
                                fileFullUrl: item,
                                fileType: fileType,
                                isImg: this.imgFormat.includes(fileType)
                            }
                        } else {
                            const fileType = this.getFileFormat(item);
                            return {
                                fileUrl: item,
                                fileBaseUrl: this.baseUrl,
                                fileFullUrl: this.baseUrl + '/' + item,
                                fileType: fileType,
                                isImg: this.imgFormat.includes(fileType)
                            }
                        }
                    })
                } else {
                    this.fileList = [];
                }
            }
        }
    },
    computed: {
        defaultFileFormat() {
            return this.fileFormat ? this.fileFormat.map(item => item.toLowerCase()) : null;
        }
    },
    methods: {
        // 删除图片
        deleteImg(index, fileUrl) {
            this.fileList.splice(index, 1);
            this.$emit('change', this.fileList);
            this.$emit('delete', fileUrl);
        },
        getInputFileChange(event) {
            // 限制上传数量
            if (this.limit && this.limit < (this.fileList.length + event.target.files.length)) {
                this.$message.warning(`超过上传${this.title}的最大数量限制!`);
                return;
            }

            event.target.files.forEach(file => {
                this.privateUploadFunction(file);
            })
            this.$refs.myInputFileRef.value = null;
        },

        // 上传附件api
        privateUploadFunction(file) {
            this.loading = true;
            var formData = new FormData();
            const fileName = this.getFileFormat(file.name);
            // 验证文件格式
            if (this.defaultFileFormat && this.defaultFileFormat.length && !this.defaultFileFormat.includes(fileName)) {
                this.loading = false;
                this.$message.warning(`请上传${this.defaultFileFormat.join(',')}的${this.title}!`);
                return;
            }
            formData.append('file', file, file.name);
            formData.append('useDay', 1);
            formData.append('path', this.path);
            formData.append('projectId', process.env.VUE_APP_FILE_SERVICE_ID);
            PublicUploadFileItemZip(formData)
            .then(data => {
                this.loading = false;
                if (data.code == 200) {
                    data.data.forEach(item => {
                        const fileType = this.getFileFormat(item.fileUrl);
                        this.fileList.push({
                            fileUrl: item.fileUrl,
                            fileBaseUrl: item.ip,
                            fileFullUrl: item.ip + '/' + item.fileUrl,
                            fileName: item.originalFilename,
                            fileType: fileType,
                            isImg: this.imgFormat.includes(fileType)
                        });
                    })
                    
                    this.$emit('change', this.fileList);
                    this.$emit('success', data.data);
                } else {
                    this.$message.error(`${this.title}上传失败!`);
                }
            })
            .catch(error => {
                this.loading = false;
                this.$message.error(error);
            })
        },
        getFileFormat(fileString) {
            let filename = fileString;
            let index1 = filename.lastIndexOf('.');
            let index2 = filename.length;
            return filename.substring(index1 + 1, index2).toLowerCase();
        }
    }
}
</script>

<style lang="scss" scoped>
.my_uploader {

    .my_uploader_content {
        display: inline-block;
    }

    .uploader_box {
        width: 100px;
        height: 100px;
        border-radius: 6px;
        vertical-align: top;
        box-sizing: border-box;
        background-color: #fbfdff;
        border: 1px dashed #c0ccda;

        .uploader_icon {
            font-size: 67px;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        &:hover {
            border-color: #409eff;
        }
    }

    .my_file_input {
        opacity: 0;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

    .preview_box {
        padding: 0;
        margin: 0 -10px;
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;
        
        .preview_img {
            margin: 10px;
            width: 100px;
            height: 100px;
            flex: 0 0 100px;
            border-radius: 4px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: 1px dashed #DCDFE6;

            .el-icon-delete {
                top: 2px;
                right: 2px;
                color: #87898f;
            }

            &.has_bgimg {
                background: url('http://ehrhz.oss-cn-hangzhou.aliyuncs.com/carhr/carhrwechat/carhrImages/carhrImg/carhr-schImg/icon/icon-system-file-thumb.svg') no-repeat center;
                background-size: 60%;
            }

            &.none_preview {
                color: white;
                font-weight: 700;
            }
        }
    }
}
::v-deep .el-image {
    width: 100%;
    height: 100%;
}
</style>
